package com.davy.gridpoint.qlxj;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.davy.gridpoint.BaseActivity;
import com.davy.gridpoint.R;
import com.davy.gridpoint.utils.ImageUtil;
import com.davy.gridpoint.utils.LogUtils;
import com.davy.gridpoint.utils.StringUtils;
import com.davy.gridpoint.view.CustomImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TakeActivity extends BaseActivity {
    private Camera camera;
    private ImageView onClickCamera;
    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    private boolean isCamera = true;
    private TextView tvTitle;
    private Map rw_item;
    private int istype = -1;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置只竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_takephotos);
        statusBar();
        rw_item = new HashMap();
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("拍照");
        findViewById(R.id.imgBack).setOnClickListener(v -> finish());
        surfaceView = findViewById(R.id.camera_preview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(surfaceHolderCallback);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        istype = getIntent().getIntExtra("istype", -1);
        if (istype == 1) {
            rw_item = (Map) getIntent().getSerializableExtra("rw_item");
            LogUtils.e("TAG", "rw_item:" + rw_item.toString());
        }
        onClickCamera = findViewById(R.id.onClickCamera);
        onClickCamera.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (camera == null) {
                return;
            }
            if (isCamera) {
                isCamera = false;
                takePicture();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void statusBar() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//显示状态栏

        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    private SurfaceHolder.Callback surfaceHolderCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera = Camera.open();
                Camera.Parameters parameters = camera.getParameters();

                // 设置相机分辨率
                List<Camera.Size> supportedSizes = parameters.getSupportedPreviewSizes();
                Camera.Size optimalSize = getOptimalPreviewSize(supportedSizes, getResources().getDisplayMetrics().widthPixels,
                        getResources().getDisplayMetrics().heightPixels);
                if (optimalSize != null) {
                    parameters.setPictureSize(optimalSize.width, optimalSize.height); // 设置成你需要的尺寸 3504*4672
                    parameters.setPreviewSize(optimalSize.width, optimalSize.height);
                    LogUtils.e("TAG", optimalSize.width + "-----------------" + optimalSize.height);
                }
                parameters.setPreviewFormat(ImageFormat.NV21);
                // 设置曝光度
                parameters.setExposureCompensation(parameters.getExposureCompensation()); // 设置成你需要的曝光度
                // 设置白平衡
                parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO); // 设置成你需要的白平衡模式
                // 设置对焦模式
//                List<String> supportedFocusModes = parameters.getSupportedFocusModes();
//                LogUtils.e("TAG", "supportedFocusModes:" + supportedFocusModes.toString());
//                if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
//                    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
//                    LogUtils.e("TAG", "是否对焦");
//                }

                camera.setDisplayOrientation(90);
                parameters.setRotation(90);

                camera.setParameters(parameters);
                camera.setPreviewDisplay(holder);
                camera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // Handle surface changes
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (camera != null) {
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        }
    };

    // 获取最佳预览尺寸
    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int width, int height) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) width / height;
        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;
        // 遍历支持的预览尺寸，选择与目标宽高比最接近的尺寸
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;
            if (Math.abs(size.height - height) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - height);
            }
        }
        // 如果没有找到与目标宽高比最接近的尺寸，选择高度最接近的尺寸
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - height) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - height);
                }
            }
        }
        return optimalSize;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }

    public void takePicture() {
        camera.takePicture(null, null, (data, camera) -> {
            // 处理拍照数据
            Bitmap bitmap = convertByteToBitmap(data);
            if (bitmap != null) {
                Bitmap mp = ImageUtil.drawTextToLeftTop(TakeActivity.this, bitmap,
                        StringUtils.getTimeS() + "", 22, R.color.black, 10, 10);
                imgDialog(mp, camera);
            } else {
                isCamera = true;
            }
        });
    }

    public void imgDialog(Bitmap bitmap, Camera camera) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TakeActivity.this);
        AlertDialog dialog = builder.create();
        // 显示对话框前，设置全屏
        dialog.setOnShowListener(d -> {
            // 获取对话框窗口
            Window window = dialog.getWindow();
            if (window != null) {
                // 设置窗口的属性以全屏显示
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                window.setBackgroundDrawableResource(android.R.color.transparent);
            }
        });

        LayoutInflater inflater = LayoutInflater.from(TakeActivity.this);
        View v = inflater.inflate(R.layout.dialog_img_new, null);
        ImageView tvClose = v.findViewById(R.id.tvClose);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvSave = v.findViewById(R.id.tvSave);
        CustomImageView imgYu = v.findViewById(R.id.imgYu1);
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }

        // 设置按键监听器
        dialog.setOnKeyListener((dialog1, keyCode, event) -> {
            // 如果是返回键，并且是按下动作（避免重复事件）
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                // 返回true表示事件被消费，不再传递
                return true;
            }
            return false;
        });

        //自定义的东西
        dialog.getWindow().setContentView(v);

        Glide.with(TakeActivity.this)
                .load(bitmap).error(R.mipmap.icon_error)
                .into(imgYu);

        tvClose.setOnClickListener(v1 -> {
            isCamera = true;
            camera.startPreview(); // 重新开始预览
            dialog.dismiss();
        });
        tvDelete.setOnClickListener(view -> {
            isCamera = true;
            camera.startPreview(); // 重新开始预览
            dialog.dismiss();
        });

        tvSave.setOnClickListener(view -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            isCamera = true;
            String path = saveImage(TakeActivity.this, bitmap);
            if (!StringUtils.isEmpty(path)) {
                Intent intent = new Intent();
                intent.putExtra("data", path);
                setResult(RESULT_OK, intent);

                finish();
                dialog.dismiss();
            }
        });
    }

    //保存图片
    public String saveImage(Context context, Bitmap bmp) {
        // 首先保存图片 创建文件夹
        LogUtils.e("TAG", "----" + Environment.getExternalStorageDirectory());
        File appDir = new File(Environment.getExternalStorageDirectory(), "Davy");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        //图片文件名称
        String fileName = "grid_" + System.currentTimeMillis() + ".jpeg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 33, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        String path = file.getAbsolutePath();
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        return path + "";
    }

    //byte[]转Bitmap
    public Bitmap convertByteToBitmap(byte[] data) {
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }
}